package com.toe.order.webapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.toe.commodity.service.CommodityGoodsService;
import com.toe.commodity.service.CommodityGoodsSpecificationsService;
import com.toe.common.exception.NoRollbackForToeServiceException;
import com.toe.common.exception.ToeServiceException;
import com.toe.common.pojo.ali.Alipay;
import com.toe.common.restful.JsonPage;
import com.toe.common.restful.StateEnum;
import com.toe.order.service.OrderGoodsService;
import com.toe.order.webapi.mapper.OrderCartMapper;
import com.toe.order.webapi.mapper.OrderGoodsMapper;
import com.toe.order.webapi.repository.IOrderGoodsRedisRepository;
import com.toe.common.utils.AliPayEnum;
import com.toe.common.utils.AliPayUtil;
import com.toe.common.utils.SnowFlakeUtil;
import com.toe.common.utils.TimeUtil;
import com.toe.pojo.dto.order.AddCartOrderGoodsDTO;
import com.toe.pojo.dto.order.AddOrderGoodsDTO;
import com.toe.pojo.dto.order.OrderPayDTO;
import com.toe.pojo.entity.order.OrderCart;
import com.toe.pojo.entity.order.OrderGoods;
import com.toe.pojo.vo.commodity.CommodityGoodsSpecificationsVO;
import com.toe.pojo.vo.commodity.CommodityOrderGoodsVO;
import com.toe.pojo.vo.order.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陶涛
 * @since 2022-07-19
 */
@Service
@Transactional(noRollbackFor = NoRollbackForToeServiceException.class)
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements OrderGoodsService {

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private OrderCartMapper orderCartMapper;

    @Autowired
    private IOrderGoodsRedisRepository redisRepository;

//    @DubboReference
//    BusinessInformationService dubboBusinessService;

    @DubboReference
    private CommodityGoodsService dubboGoodsService;

    @DubboReference
    private CommodityGoodsSpecificationsService dubboGoodsSpecificationsService;

    private static final SnowFlakeUtil orderNumber = new SnowFlakeUtil(
            0, 0, 1480166465631L);

    /**
     * 添加新订单
     * @param addOrderGoodsDTO
     */
    public Long addNewOrder(AddOrderGoodsDTO addOrderGoodsDTO) {
        CommodityGoodsSpecificationsVO specifications =
                dubboGoodsSpecificationsService.getSpecificationsById(
                        addOrderGoodsDTO.getSpecificationId());
        if (specifications == null) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "服务器忙,请稍后重试");
        }

        OrderGoods orderGoods = dtoToEntity(addOrderGoodsDTO, specifications);

        int rows = orderGoodsMapper.insert(orderGoods);
        if (rows == 0) {
            throw new ToeServiceException(
                    StateEnum.ERR_SERVER_ERROR, "添加订单失败,服务器忙,请稍后重试");
        }
        return orderGoods.getId();
    }

    /**
     * 购物车生成订单
     * @param addOrderGoodsDTOS
     */
    public Long addCartOrder(AddCartOrderGoodsDTO addOrderGoodsDTOS) {
        List<Long> cartIds = new ArrayList<>(addOrderGoodsDTOS.getCartIds());

        List<OrderCart> orderCarts = orderCartMapper.listByIds(cartIds);
        List<Long> ids = new ArrayList<>();
        for (OrderCart orderCart : orderCarts) {
            ids.add(orderCart.getSpecificationsId());
        }

        List<CommodityGoodsSpecificationsVO> goodsByIds =
                dubboGoodsSpecificationsService.listSpecificationsByIds(ids);
        System.out.println("=============goodsByIds============");
        System.out.println(goodsByIds);

        List<OrderGoods> addList = new ArrayList<>();
        Map<Long, CommodityGoodsSpecificationsVO> goodsMap = new HashMap<>();
        for (CommodityGoodsSpecificationsVO goods : goodsByIds) {
            goodsMap.put(goods.getId(), goods);
        }
        System.out.println("=============goodsMap============");
        System.out.println(goodsMap);

        String orderNumber = OrderGoodsServiceImpl.orderNumber.getSnowFlakeNumber();
        for (OrderCart orderCart : orderCarts) {

            System.out.println("=============orderCart============");
            System.out.println("orderCart: "+orderCart);
            CommodityGoodsSpecificationsVO goodsMapValue =
                    goodsMap.get(orderCart.getSpecificationsId());

            AddOrderGoodsDTO addOrderGoods = new AddOrderGoodsDTO();
            BeanUtils.copyProperties(orderCart, addOrderGoods);
            addOrderGoods.setShippingAddress(addOrderGoodsDTOS.getShippingAddress());
            addOrderGoods.setNote(addOrderGoodsDTOS.getNote());
            addOrderGoods.setSpecificationId(orderCart.getSpecificationsId());
            addOrderGoods.setNumber(orderCart.getCount());
            System.out.println("=============mapValue============");
            System.out.println(goodsMapValue);
            OrderGoods orderGoods = dtoToEntity(
                    addOrderGoods, goodsMapValue, orderNumber);

            addList.add(orderGoods);
        }

        int rows = orderGoodsMapper.insertAll(addList);
        System.out.println(addList.get(0).getId());
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "生成订单失败,请稍后重试");
        }

        orderCartMapper.deleteByIds(cartIds);
        return addList.get(0).getId();
    }

    /**
     * 删除订单
     * @param orderId
     */
    public void deleteByOrderId(Long orderId) {
        OrderGoods order = orderGoodsMapper.selectById(orderId);
        if (order == null || order.getIsDelete() == 1) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "订单不存在");
        }

        int rows = orderGoodsMapper.deleteById(orderId);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "删除失败,服务器忙,请稍后重试");
        }

        // 更新缓存
        if (redisRepository.hasDetailsData(orderId)) {
            redisRepository.deleteDetailsValue(orderId);
        }
    }

    /**
     * 通过订单id查询订单详情信息
     * @param orderId
     * @return
     */
    public OrderGoodsDetailsVO getOrderDetails(Long orderId) {
        System.out.println("---------------进来了---------------");
        OrderGoodsDetailsVO orderGoodsDetails;

        // redis缓存
        // formatType格式为yyyy-MM-dd HH:mm:ss
        // yyyy年MM月dd日 HH时mm分ss秒
        if (redisRepository.hasDetailsData(orderId)) {
            orderGoodsDetails = redisRepository.getOrderDetails(orderId);
            if (orderGoodsDetails != null) {
//                System.out.println("-----createTime: " + orderGoodsDetails.getCreateTime());

                if (orderGoodsDetails.getState() == 0
                        && orderGoodsDetails.getIsDelete() == 0) {
                    String time = null;
                    try {
                        time = TimeUtil.getRemainingPayTime(
                                TimeUtil.strToLocalDateTime(
                                        orderGoodsDetails.getCreateTime()
                                ).plusMinutes(15));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (time == null) {
                        System.out.println("--------------没有设置时间--------------");
                        Integer rows = updateIsEnable(orderGoodsDetails.getId());
                        if (rows == 0) {
                            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                                    "服务器忙,请稍后重试");
                        }

                        // 修改缓存中的值
                        orderGoodsDetails.setState(2);
                        redisRepository.saveDetailsValue(orderGoodsDetails);
                    } else {
                        System.out.println("--------------开始设置时间--------------");
                        orderGoodsDetails.setRemainingPayTime(time);
                    }
                }
                System.out.println("--------------返回缓存中的值---------------");
                return orderGoodsDetails;
            }
        }

        // 开始数据库查询
        OrderGoods orderGoods = orderGoodsMapper.selectById(orderId);

        if (orderGoods == null || orderGoods.getIsDelete() == 1) {
            redisRepository.saveDetailsEmptyValue(orderId);
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "订单不存在");
        }

//        System.out.println("-----数据库查询的createTime: "
//                + orderGoods.getCreateTime());
        orderGoodsDetails = new OrderGoodsDetailsVO();
        BeanUtils.copyProperties(orderGoods, orderGoodsDetails);
        // 储存时间
        orderGoodsDetails.setCreateTime(TimeUtil.dateToString(
                orderGoods.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        orderGoodsDetails.setPayTime(TimeUtil.dateToString(
                orderGoods.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
        orderGoodsDetails.setDeliveryTime(TimeUtil.dateToString(
                orderGoods.getDeliveryTime(), "yyyy-MM-dd HH:mm:ss"));
        orderGoodsDetails.setReceivingTime(TimeUtil.dateToString(
                orderGoods.getReceivingTime(), "yyyy-MM-dd HH:mm:ss"));
//        System.out.println("-----存入的createTime: "
//                + orderGoodsDetails.getCreateTime());

        System.out.println("==========开始查询商品==========");
        CommodityOrderGoodsVO goods =
                dubboGoodsService.getOrderGoodsById(
                        orderGoods.getGoodsId(),
                        orderGoods.getSpecificationId());
//        System.out.println("================查询没有异常==============");
        System.out.println("goods -> " + goods);
        orderGoodsDetails.setGoodsTitle(goods.getTitle());
        orderGoodsDetails.setGoodsType(goods.getTypeName());
        orderGoodsDetails.setGoodsCover(goods.getCover());
        orderGoodsDetails.setSpecification(goods.getSpecifications());
//        orderGoodsDetails.setBusinessId(goods.getBusinessId());

        BigDecimal num = new BigDecimal(orderGoods.getNumber());
        BigDecimal price = num.multiply(goods.getPrice());
        orderGoodsDetails.setPrice(goods.getPrice());
        orderGoodsDetails.setTolPrice(price);

//        BusinessInformation business =
//                dubboBusinessService.getById(goods.getBusinessId());
//        orderGoodsDetails.setBusinessName(business.getName());

        System.out.println("=====开始设置剩余时间=====");
        if (orderGoods.getIsDelete() == 0
                && orderGoods.getState() == 0) {
            System.out.println("进来设置");
            String time = TimeUtil.getRemainingPayTime(
                    orderGoods.getCreateTime());
            if (time == null) {
                Integer rows = updateIsEnable(orderGoods.getId());
                if (rows == 0) {
                    throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                            "服务器忙,请稍后重试");
                }
                orderGoodsDetails.setState(2);
            } else {
                orderGoodsDetails.setRemainingPayTime(time);
            }
        }
        System.out.println("设置完毕: " + orderGoodsDetails.getRemainingPayTime());

        redisRepository.saveDetailsValue(orderGoodsDetails);

        System.out.println("---------------返回数据库的值---------------");
        return orderGoodsDetails;
    }

    /**
     * 查询该用户的所有订单
     * @param userId
     * @return
     */
    public JsonPage<OrderGoodsSimpleVO> listAllOrderByUserId(
            Long userId, int pageNum, int pageSize) {

        System.out.println("进来了pageNum: " + pageNum + "  pageSize: " + pageSize);
        PageHelper.startPage(pageNum, pageSize);

        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_delete", 0);

        System.out.println("开始分页");
        List<OrderGoods> order = orderGoodsMapper.selectList(wrapper);
        System.out.println("---------------------size: " + order.size());

        return getSimpleOrder(order);

    }

    /**
     * 查询该用户所有取消的订单
     * @param userId
     * @return
     */
    public JsonPage<OrderGoodsSimpleVO> listCancelOrderByUserId(
            Long userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_delete", 0)
                .and(wq -> wq
                        .eq("state", 1)
                        .or()
                        .eq("state", 2)
                );
        List<OrderGoods> order = orderGoodsMapper.selectList(wrapper);

        return getSimpleOrder(order);
    }

    /**
     * 查询该用户已支付的所有订单
     *
     * @param userId
     * @return
     */
    public JsonPage<OrderGoodsSimpleVO> listPayOrderByUserId(
            Long userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_delete", 0)
                .eq("state", 3);
        List<OrderGoods> order = orderGoodsMapper.selectList(wrapper);

        return getSimpleOrder(order);
    }

    /**
     * 查询该用户待支付的所有订单
     *
     * @param userId
     * @return
     */
    public JsonPage<OrderGoodsSimpleVO> listNotPayOrderByUserId(
            Long userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_delete", 0)
                .eq("state", 0);
        List<OrderGoods> order = orderGoodsMapper.selectList(wrapper);

        return getSimpleOrder(order);
    }

//    /**
//     * 电脑网页支付功能
//     *
//     * @param payDTO
//     * @param httpResponse
//     */
//    public void pay(OrderPayDTO payDTO, HttpServletResponse httpResponse) {
////        System.out.println("orderId -> " + orderId);
//        List<OrderGoods> orderGoodsList = orderGoodsMapper.listByIds(payDTO.getOrderIds());
////        System.out.println("不为空");
//
//        if (isOrderError(orderGoodsList)) {
////            System.out.println("进来了");
//            List<QueryGoodsAndSpecifications> ids = new ArrayList<>();
//            BigDecimal price = new BigDecimal("0");
//            for (OrderGoods orderGoods : orderGoodsList) {
//                QueryGoodsAndSpecifications query = new QueryGoodsAndSpecifications();
//                query.setGoodsId(orderGoods.getGoodsId());
//                query.setSpecificationId(orderGoods.getSpecificationId());
//                ids.add(query);
//                price = price.add(orderGoods.getPrice());
//            }
//            ids = ids.stream().distinct().collect(Collectors.toList());
//
//            List<CommodityOrderGoodsVO> goods = dubboGoodsService.listOrderGoodsByIds(ids);
//            StringBuilder title = new StringBuilder();
//            StringBuilder specification = new StringBuilder();
//            for (int i = 0; i < goods.size(); i++) {
//                if (i == goods.size()-1) {
//                    title.append(goods.get(i).getTitle());
//                    specification.append(goods.get(i).getSpecifications());
//                } else {
//                    title.append(goods.get(i).getTitle()).append("+");
//                    specification
//                            .append(goods.get(i).getSpecifications())
//                            .append("+");
//                }
//            }
//
//            Alipay alipay = new Alipay();
////            System.out.println("开始查询");
////            System.out.println("goodsId: " + orderGoods.getGoodsId());
////            System.out.println("specificationId");
//            alipay.setTitle(title.toString());
//            alipay.setPrice(price);
//            alipay.setSpecification(specification.toString());
//            alipay.setReturnUrl(payDTO.getReturnUrl());
//            alipay.setUrl(AliPayEnum.ORDER_GOODS.getType());
//
//            AliPayUtil.pay(alipay, httpResponse);
//        }
//    }

    /**
     * 电脑网页支付功能
     *
     * @param orderId
     * @param httpResponse
     */
    public void pay(Long orderId, String returnUrl, HttpServletResponse httpResponse) {
//        System.out.println("orderId -> " + orderId);
        OrderGoods orderGoods = orderGoodsMapper.selectById(orderId);
        if (isOrderError(orderGoods)) {
            CommodityOrderGoodsVO goods = dubboGoodsService.getOrderGoodsById(
                    orderGoods.getGoodsId(), orderGoods.getSpecificationId());
            String title = goods.getTitle() + "...";
            String specifications = goods.getSpecifications() + "...";

            QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("order_number", orderGoods.getOrderNumber());
            List<OrderGoods> list = orderGoodsMapper.selectList(wrapper);
            BigDecimal price = new BigDecimal("0");
            for (OrderGoods g : list) {
                price = price.add(g.getPrice());
            }

            Alipay alipay = new Alipay();
            BeanUtils.copyProperties(orderGoods, alipay);
            alipay.setTitle(title);
            alipay.setPrice(price);
            alipay.setSpecification(specifications);

            alipay.setUrl(AliPayEnum.ORDER_GOODS.getType());
            alipay.setReturnUrl(returnUrl);
            System.out.println("-----------跳转页面 -> "+returnUrl);

            AliPayUtil.pay(alipay, httpResponse);
        }
    }

    /**
     * 手机端支付
     *
     * @param orderId
     * @param httpResponse
     */
    public void phonePay(Long orderId, HttpServletResponse httpResponse) {
        System.out.println("orderId -> " + orderId);
        OrderGoods orderGoods = orderGoodsMapper.selectById(orderId);
        if (isOrderError(orderGoods)) {
            System.out.println("进来了");
            Alipay alipay = new Alipay();
            BeanUtils.copyProperties(orderGoods, alipay);
            System.out.println("开始查询");
            System.out.println("goodsId: " + orderGoods.getGoodsId());
            System.out.println("specificationId");
            CommodityOrderGoodsVO goods = dubboGoodsService.getOrderGoodsById(
                    orderGoods.getGoodsId(), orderGoods.getSpecificationId());
            System.out.println("title -> " + goods.getTitle());
            alipay.setTitle(goods.getTitle());
            alipay.setPrice(orderGoods.getPrice());
            alipay.setSpecification(goods.getSpecifications());

            alipay.setUrl(AliPayEnum.ORDER_GOODS.getType());

            AliPayUtil.phonePay(alipay, httpResponse);
        }
    }

    /**
     * 手机端app支付
     *
     * @param orderId
     * @param httpResponse
     */
    public void appPay(Long orderId, HttpServletResponse httpResponse) {
        System.out.println("orderId -> " + orderId);
        OrderGoods orderGoods = orderGoodsMapper.selectById(orderId);
        if (isOrderError(orderGoods)) {
            System.out.println("进来了");
            Alipay alipay = new Alipay();
            BeanUtils.copyProperties(orderGoods, alipay);
            System.out.println("开始查询");
            System.out.println("goodsId: " + orderGoods.getGoodsId());
            System.out.println("specificationId");
            CommodityOrderGoodsVO goods = dubboGoodsService.getOrderGoodsById(
                    orderGoods.getGoodsId(), orderGoods.getSpecificationId());
            System.out.println("title -> " + goods.getTitle());
            alipay.setTitle(goods.getTitle());
            alipay.setPrice(orderGoods.getPrice());
            alipay.setSpecification(goods.getSpecifications());

            alipay.setUrl(AliPayEnum.ORDER_GOODS.getType());

            AliPayUtil.appPay(alipay, httpResponse);
        }
    }

    /**
     * 支付功能的同步调用
     *
     * @param orderId
     * @param request
     */
    public void returnUrl(Long orderId, HttpServletRequest request) {
        String state = AliPayUtil.returnUrl(request);
        Map<String, String> payStateMap = AliPayUtil.getAlipayInformation(request);
        System.out.println("===================================结束同步回调===============================");
        if ("ok".equals(state)) {
            OrderGoods queryGoods = orderGoodsMapper.selectById(orderId);
            QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("order_number", queryGoods.getOrderNumber());
            List<OrderGoods> list = orderGoodsMapper.selectList(wrapper);
            List<Long> orderIds = new ArrayList<>();
            for (OrderGoods orderGoods : list) {
                orderIds.add(orderGoods.getId());
            }

            for (Long id : orderIds) {
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setId(id);
                orderGoods.setAlipayNumber(payStateMap.get("trade_no"));
                orderGoods.setState(3);

                try {
                    orderGoods.setPayTime(TimeUtil
                            .strToDate(payStateMap.get("notify_time"),
                                    "yyyy-MM-dd HH:mm:ss"));
                } catch (ParseException e) {
                    refund(id);
                    throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                            "服务器忙,请稍后重试");
                }

                orderGoods.setUpdateTime(TimeUtil
                        .localDateTimeToDate(LocalDateTime.now()));
                orderGoodsMapper.updateById(orderGoods);
                redisRepository.deleteDetailsValue(id);
            }
        } else {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "发生未知错误,支付失败");
        }

    }

    /**
     * 退款
     *
     * @param orderId
     */
    public void refund(Long orderId) {
        OrderGoods orderGoods = orderGoodsMapper.selectById(orderId);

        String state = null;
        if (orderGoods.getState() == 3) {
            Alipay alipay = new Alipay();
            BeanUtils.copyProperties(orderGoods, alipay);
            CommodityOrderGoodsVO goods = dubboGoodsService.getOrderGoodsById(
                    orderGoods.getGoodsId(), orderGoods.getSpecificationId());
            alipay.setTitle(goods.getTitle());
            BigDecimal num = new BigDecimal(orderGoods.getNumber());
            BigDecimal price = num.multiply(goods.getPrice());
            alipay.setPrice(price);

            state = AliPayUtil.refund(alipay);
        } else {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "退款失败,该订单未付款");
        }

        if ("ok".equals(state)) {
            OrderGoods updateOrder = new OrderGoods();
            updateOrder.setId(orderId);
            updateOrder.setState(4);
            int rows = orderGoodsMapper.updateById(updateOrder);

            if (rows == 0) {
                throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                        "发生未知错误,退款失败,请联系工作人员");
            }
        } else {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "发生未知错误,退款失败,请联系工作人员");
        }

    }

    /**
     * dto转换成实体类的方法
     * @param addOrderGoodsDTO
     * @param goods
     * @return
     */
    private OrderGoods dtoToEntity(AddOrderGoodsDTO addOrderGoodsDTO, CommodityGoodsSpecificationsVO goods) {
        return dtoToEntity(addOrderGoodsDTO, goods, orderNumber.getSnowFlakeNumber());
    }

    /**
     * dto转换成实体类的方法
     * @param addOrderGoodsDTO
     * @param goods
     * @return
     */
    private OrderGoods dtoToEntity(AddOrderGoodsDTO addOrderGoodsDTO, CommodityGoodsSpecificationsVO goods, String orderNumber) {
        OrderGoods orderGoods = new OrderGoods();
        BeanUtils.copyProperties(addOrderGoodsDTO, orderGoods);

        System.out.println();
        System.out.println(addOrderGoodsDTO);
        BigDecimal price = goods.getPrice()
                .multiply(new BigDecimal(orderGoods.getNumber()));
        orderGoods.setPrice(price);

        orderGoods.setIsDelete(0);
        orderGoods.setState(0);
        orderGoods.setIsDelivery(0);
        orderGoods.setIsReceived(0);

        orderGoods.setOrderNumber(orderNumber);

        LocalDateTime localDateTime = LocalDateTime.now();
        Date date = Date.from(localDateTime
                .atZone(ZoneId.systemDefault())
                .toInstant());
        orderGoods.setCreateTime(date);
        orderGoods.setUpdateTime(date);

        return orderGoods;
    }

    /**
     * 判断订单是否可用的方法
     *
     * @param orderGoods
     * @return
     */
    private Boolean isOrderError(OrderGoods orderGoods) {
        if (orderGoods == null || orderGoods.getIsDelete() == 1) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "订单不存在");
        }

        if (orderGoods.getState() == 4) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "订单已退款");
        }

        if (orderGoods.getState() == 3) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "订单已支付");
        }

        if (orderGoods.getState() == 1) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_CLOSE,
                    "您已取消订单");
        }

        if (orderGoods.getState() == 0) {
            LocalDateTime endTime = TimeUtil
                    .dateToLocalDateTime(
                            orderGoods.getCreateTime())
                    .plusMinutes(15);
            LocalDateTime nowTime = LocalDateTime.now();
            if (nowTime.isAfter(endTime)) {
                Integer rows = updateIsEnable(orderGoods.getId());
                if (rows == 0) {
                    throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                            "服务器忙,请稍后重试");
                }
                orderGoods.setState(2);
            }
        }

        if (orderGoods.getState() == 2) {
            throw new NoRollbackForToeServiceException(
                    StateEnum.ERR_SERVER_ERROR, "支付超时,订单已取消");
        }

        return true;
    }

    /**
     * 判断订单列表是否可用的方法
     * @param orderGoodsList
     * @return
     */
    private Boolean isOrderError(List<OrderGoods> orderGoodsList) {
        for (OrderGoods orderGoods : orderGoodsList) {
            isOrderError(orderGoods);
        }

        return true;
    }

    /**
     * 获取订单基本信息的方法
     *
     * @param order
     * @return
     */
    private JsonPage<OrderGoodsSimpleVO> getSimpleOrder(List<OrderGoods> order) {
        System.out.println("===============开始解析===============");
        JsonPage<OrderGoods> queryPage = JsonPage.restPage(new PageInfo<>(order));
        Integer queryPagePageNum = queryPage.getPageNum();
        Integer queryPagePageSize = queryPage.getPageSize();
        Integer queryTotalPages = queryPage.getTotalPages();
        Long queryTotalCount = queryPage.getTotalCount();

//        order.forEach(System.out::println);
        List<OrderGoodsSimpleVO> list = new ArrayList<>();
        JsonPage<OrderGoodsSimpleVO> resultPage =
                JsonPage.restPage(new PageInfo<>(list));
//        System.out.println("order -> "+order);
        System.out.println("order.size() = " + order.size());
        if (order.size() == 0) return resultPage;

        List<QueryGoodsAndSpecifications> goodsIds = new ArrayList<>();
        for (OrderGoods orderGoods : order) {
            QueryGoodsAndSpecifications query = new QueryGoodsAndSpecifications();
            query.setGoodsId(orderGoods.getGoodsId());
            query.setSpecificationId(orderGoods.getSpecificationId());
            System.out.println("orderGoods.getSpecificationId: "
                    + orderGoods.getSpecificationId());
            System.out.println("query: " + query.getSpecificationId());
            goodsIds.add(query);
        }

        goodsIds = goodsIds.stream().distinct().collect(Collectors.toList());

        System.out.println("去重后: " + goodsIds.size());
        goodsIds.forEach(System.out::println);
        List<CommodityOrderGoodsVO> goods =
                dubboGoodsService.listOrderGoodsByIds(goodsIds);
        System.out.println("goods -> ");
        goods.forEach(s -> System.out.println(s.getBusinessId()));

//        List<Long> businessIds = new ArrayList<>();
        Map<Long, CommodityOrderGoodsVO> goodsMap = new HashMap<>();
        for (CommodityOrderGoodsVO good : goods) {
            goodsMap.put(good.getId(), good);
//            businessIds.add(good.getBusinessId());
        }
//        businessIds = businessIds.stream().distinct()
//                .collect(Collectors.toList());
//        System.out.println("businessId: ");
//        businessIds.forEach(System.out::println);
//        List<BusinessInformation> business =
//                dubboBusinessService.listByIds(businessIds);

//        Map<Long, BusinessInformation> businessMap = new HashMap<>();
//        for (BusinessInformation businessInformation : business) {
//            businessMap.put(businessInformation.getId(), businessInformation);
//        }
        goodsMap.entrySet().forEach(System.out::println);
        for (OrderGoods orderGoods : order) {
            OrderGoodsSimpleVO orderGoodsSimpleVO = new OrderGoodsSimpleVO();
            BeanUtils.copyProperties(orderGoods, orderGoodsSimpleVO);

            Long goodsId = orderGoods.getGoodsId();
            CommodityOrderGoodsVO goodsValue = goodsMap.get(goodsId);
            if (goodsValue != null) {
                orderGoodsSimpleVO.setSpecification(goodsValue.getSpecifications());
                orderGoodsSimpleVO.setGoodsTitle(goodsValue.getTitle());
                orderGoodsSimpleVO.setGoodsCover(goodsValue.getCover());

                BigDecimal num = new BigDecimal(orderGoods.getNumber());
                BigDecimal price = num.multiply(goodsValue.getPrice());
                orderGoodsSimpleVO.setPrice(goodsValue.getPrice());
                orderGoodsSimpleVO.setTolPrice(price);

//                Long businessId = goodsValue.getBusinessId();
//                BusinessInformation businessValue = businessMap.get(businessId);
//                orderGoodsSimpleVO.setBusinessId(businessId);
//                orderGoodsSimpleVO.setBusinessName(businessValue.getName());

                // 查询订单剩余支付时间
                if (orderGoods.getState() == 0
                        && orderGoods.getIsDelete() == 0) {
                    String time = TimeUtil.getRemainingPayTime(orderGoods.getCreateTime());
                    if (time == null) {
                        Integer rows = updateIsEnable(orderGoods.getId());
                        if (rows == 0) {
                            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                                    "服务器忙,请稍后重试");
                        }
                        orderGoodsSimpleVO.setState(2);
                    } else {
                        orderGoodsSimpleVO.setRemainingPayTime(time);
                    }
                }
            }
            list.add(orderGoodsSimpleVO);
        }

        resultPage.setList(list);
        resultPage.setPageNum(queryPagePageNum);
        resultPage.setPageSize(queryPagePageSize);
        resultPage.setTotalPages(queryTotalPages);
        resultPage.setTotalCount(queryTotalCount);
        return resultPage;
    }

    /**
     * 系统取消订单的方法
     *
     * @param orderId
     * @return
     */
    private Integer updateIsEnable(Long orderId) {
        OrderGoods order = new OrderGoods();
        order.setId(orderId);
        order.setState(2);
        return orderGoodsMapper.updateById(order);
    }

}
